<template>
  <div class="order">
    <!-- 收货地址 -->
    <h1>收货地址</h1>
    <div class="header">
      <div class="address" @click="selected(index)" :class="address_index===index?'active':''"
        v-for="(item,index) in data.site" @mouseenter="data.site[index].isFlag = true"
        @mouseleave="data.site[index].isFlag = false">
        <div style="margin:24px 10px;">
          <!-- 定宽定高 -->
          <span>{{item.name}}</span>&nbsp;&nbsp;<span>{{item.phone}}</span>
        </div>
        <div class="AHC">
          <!-- 地址 -->
          <span class="AH">
            <span v-show="Boolean(item.tacitlyApprove)" class="addRes">默认</span>
            {{item.address}}
          </span>
        </div>
        <div class=" ico" v-show="data.site[index].isFlag">
          <el-icon @click="modification(index)">
            <Edit />
          </el-icon>
          <el-icon @click="addressRemove(index)">
            <Delete />
          </el-icon>
        </div>
      </div>
      <div @click="open" class="new">
        <img src="/images/cart/icon_添加.svg" alt="">
        <span>新增收货地址</span>
      </div>
    </div>
    <!--收货地址弹窗-->
    <div class="mask" v-show="data.flag">
      <div :class="['mask-content',data.isRemove===false?'mask-flag':'']">
        <div class="mask-content-body">
          <el-form v-show="data.isRemove===true" :model="form" label-width="120px">
            <div class="close">
              <el-icon @click="close">
                <Close />
              </el-icon>
            </div>
            <div>
              <h3>添加地址</h3>
            </div>
            <!--收件人-->
            <div>
              <el-input v-model.trim="form.recipients" @blur="recipientsBlue" placeholder="收件人" maxlength="6" />
              <div v-show="data.recipientsFlag" class="hint">
                <span>{{data.recipientsMsg}}</span>
              </div>
            </div>
            <!--手机号-->
            <div>
              <el-input @blur="phoneBlue" v-model="form.phone" placeholder="手机号" />
              <div v-show="data.phoneFlag" class="hint">
                <span>{{data.phoneMsg}}</span>
              </div>
            </div>
            <!--地址三级联动-->
            <div>
              <div class="personalData-form-inp el-form-item-inp">
                <el-select @change="province" v-model="form.province" placeholder="请选择">
                  <el-option v-for="(item,index) in data.province" :key="item.name" :label="item.name"
                    :value="item.name" />
                </el-select>
                <el-select @change="city" v-model="form.city" placeholder="请选择">
                  <el-option v-for="item in data.city" :key="item.name" :label="item.name" :value="item.name" />
                </el-select>
                <el-select v-model="form.district" placeholder="请选择">
                  <el-option v-for="item in data.district" :label="item" :value="item" />
                </el-select>
              </div>
            </div>
            <!--地址提示-->
            <div class="address_prompt">
              <el-input @blur="defaultAddressBlue" v-model.trim="form.defaultAddress" placeholder="详细地址" maxlength="120"
                @input="btnAH"/>
              <div v-show="data.defaultAddressFlag" class="hint">
                <span>{{ data.defaultAddressMsg }}</span>
              </div>
            </div>
            <!--设为默认地址-->
            <div class="default">
              <el-checkbox v-model="form.tacitlyApprove" label="设为默认地址" size="large" />
            </div>
            <!--确定-->
            <div class="confirm">
              <el-button :plain="true" @click="onSubmit">确定</el-button>
            </div>
          </el-form>
          <div v-show="data.isRemove===false" class="rem">
            <h3>确定删除该地址</h3>
            <div>
              <el-button @click="enThink">再想想</el-button>
              <el-button @click="enRemove">确定</el-button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <div class="discounts">
      <div class="discountsH">
        <div>
          <span>发票信息 </span> <span><small> 注:发票金额为现金支付金额 (扣除抵用券,积分抵用等)</small></span>
        </div>

        <div>
          <span> 发票类型 </span> <span> 个人 </span>

          <el-button text @click="opens" style="color:blue">修改></el-button>
        </div>
      </div>
      <!--      <div class="discountsW">
        <div><span>优惠券与抵用</span><img src="" alt=""><span>使用优惠券</span></div>
        <div><input type="checkbox"><span> 可使用50积分抵扣0.5元</span></div>
      </div>-->
    </div>
    <div class="payment">
      <h2 style="padding: 10px 0">商品信息</h2>
      <div class="paymentA" v-for="(item,index) in data.list" :key="index">
        <div class="paymentAA">
          <!-- /src/assets/images/cart/m303%20(1).png -->
          <img :src="item.mainimage" alt="">
          <span class="state">{{item.title}}</span>
          <span>￥{{item.price}}</span>
          <span>{{item.quantity}}</span>
        </div>
      </div>
      <hr>
    </div>
    <!-- 付款 -->
    <div class="pay">
      <div>
        <h1>应付金额:</h1>
        <span>￥{{totals}}.00</span>
        <a href="javascript:;" @click="handleOrder">
          <div class="flex">
            <el-button color="#626aef" style="width:200px;height:60px;">提交订单</el-button>
          </div>
        </a>
      </div>
    </div>
  </div>
  <!-- 固定定位结算 -->
</template>
<!-- 固定定位结算 -->

<script setup>
import {onMounted, reactive, computed, getCurrentInstance, ref, onBeforeUnmount} from 'vue';
import { ElMessage, ElMessageBox } from "element-plus";
import { useRoute,useRouter } from "vue-router";
import store from "../../../store";
const router = useRouter();
const route = useRoute();
//解析proxy
const { proxy } = getCurrentInstance();
let form = reactive({
  //收件人
  recipients:'',
  //电话
  phone:'',
  //详细地址
  defaultAddress:'',
  //是否默认
  tacitlyApprove:'',
  //省市区
  province:'',
  //市
  city:'',
  //区
  district:'',
});


let data =reactive({
      flag:'',
      name: 'Order',
      isFlag:false,
      totals: 0,
      list:[{
          id: 1,
          mainimage: "/images/cart/顺丰.png",
          title: "顺丰包邮卡",
          price: 0,
          quantity: 1
        }],
      //三级联动数组
      province : [],
      //地址数组
      site:[

      ],
      //收件人
      recipientsFlag:false,
      recipientsMsg:'请输入联系人',
      //手机号
      phoneFlag:false,
      phoneMsg:'请输入手机号',
      //详细地址
      defaultAddressFlag:false,
      defaultAddressMsg:'请输入详细地址',
      
      i:'',
      modificationFlag:'',
      isRemove:'',
      n:''
  })

// 选中地址高亮显示
let address_index = ref(0);
let selected = index=>{
  address_index.value = index;
}

// 离开该页面清除缓存数据
onBeforeUnmount(()=>{
  sessionStorage.removeItem('order');
})

// 点击提交订单
let handleOrder = ()=>{
  if (sessionStorage.getItem('order')){
    // 判断是否有收获信息
    if (data.site.length!==0){
      // console.log(data.totals);
      // 发送请求
      proxy.$post('/api/order/addOrder',{
        order: sessionStorage.getItem('order'),
        site: data.site[address_index.value],
        total: data.totals
      }).then(data=>{
        // console.log(data);
        if (data.code === 200){
          // console.log(data.order_id);
          sessionStorage.setItem('orderid',data.order_id);
          sessionStorage.removeItem('order');
          router.push('/cart/affirm');
        }else {
          ElMessage.error(data.msg);
        }

      });
    }else {
      ElMessage({
        type: 'warning',
        message: '请添加收获地址',
      })
    }
  }
}
// 总计
let totals = computed(() => {
    let total = 0
    data.list.forEach(element => {
      total+=element.price*element.quantity
    });
    data.totals = total;
    return total;
})

// 获取后端的数据
onMounted(()=>{
  data.province = store.state.province;
  PubSub.publishSync('item', 1);
  proxy.$get("/api/PersonalCenter/addressAdministration", {})
      .then((date)=>{
        // console.log(date);
        data.site=date;
        data.site.forEach((item)=>{
          item.isFlag = false;
        })
        // console.log(date);
        date.forEach((item,index)=>{
          if (item.tacitlyApprove == 1){
            address_index.value = index;
          }
        })
        // console.log(date.site);
      })
  // 获取商品信息
  let order = sessionStorage.getItem('order');
  if (order){
    // console.log(JSON.parse(order));
    data.list.unshift(...JSON.parse(order));
  }
})

// 收件人失去焦点
let recipientsBlue = ()=>{
  data.recipientsFlag = form.recipients === '';
}
//手机号失去焦点
let phoneBlue = ()=>{
  if (form.phone===''){
    data.phoneMsg = '请输入手机号';
    data.phoneFlag = true;
  }else if (/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/ig.test(form.phone)){
    data.phoneFlag = false;
  }else if (/^1([38][0-9]|4[579]|5[0-3,5-9]|6[6]|7[0135678]|9[89])\d{8}$/ig.test(form.phone)===false){
    data.phoneMsg = '请输入正确的手机号格式';
    data.phoneFlag = true;
  }
}
//地址
// var btnAHs=""
let btnAH=()=>{
  let AH = /^[\u4E00-\u9FA5|a-zA-Z|0-9]+$/
  if (AH.test(form.defaultAddress)){
   
  }else{
    form.defaultAddress = form.defaultAddress.replace(/[`~!@#$%^&*()_\-+=<>?:"{}|,.\/;'\\[\]·~！@#￥%……&*（）——\-+={}|《》？：“”【】、；‘’，。、]/g, "");
    ElMessage({
      message: '当前输入的为特殊字符，不可用',
      type: 'error',
    })
  }
}

//详细地址
let defaultAddressBlue = ()=>{
  data.defaultAddressFlag = form.defaultAddress === '';
}
//删除地址
let addressRemove = (index)=>{
  data.flag = true;
  data.n=index;
  data.isRemove = false;
}
//点击修改
let modification = (index)=>{
  data.isRemove = true;
  data.modificationFlag = true;
  //下标
  data.i = index;
  //清除弹窗
  data.flag = true;
  //赋值
  form.recipients = data.site[index].name;
  form.phone = data.site[index].phone;
  form.province = data.site[index].addressProvince;
  form.city = data.site[index].addressCity;
  form.district = data.site[index].addressDistrict;
  form.defaultAddress = data.site[index].addressDefaultAddress;
  form.tacitlyApprove = Boolean(data.site[index].tacitlyApprove);
  //
  //
  let p = data.province.findIndex((item,index)=>{
    return item.name === form.province;
  })
  data.provinceIndex = p;
  data.city=data.province[data.provinceIndex].city;
  //
  let c = data.city.findIndex((item,index)=>{
    return item.name === form.city;
  })
  data.cityIndex = c;
  data.district = data.city[data.cityIndex].districtAndCounty;
}
//地址三级联动
let province = ()=>{
  let i = data.province.findIndex((item,index)=>{
    return item.name === form.province
  })
  data.provinceIndex = i;
  data.city=data.province[data.provinceIndex].city;
  form.city='';
  form.district = '';
}
//城市
let city = ()=>{
  let i = data.city.findIndex((item,index)=>{
    return item.name === form.city
  })
  data.cityIndex = i;
  data.district = data.city[data.cityIndex].districtAndCounty;
  form.district = '';
}
//确定
const onSubmit = () => {
  if (form.recipients===''||form.phone===''||form.province===''||form.city===''||form.district===''||form.defaultAddress===''){
    ElMessage({
      message: '内容不能为空',
      type: 'error',
    })
  }else if(data.phoneFlag||data.defaultAddressFlag){
    ElMessage({
      message: '内容格式不对',
      type: 'error',
    })
  } else {
    //修改确定
    if (data.modificationFlag){
      data.site[data.i].name= form.recipients;
      data.site[data.i].phone = form.phone;
      data.site[data.i].addressProvince = form.province;
      data.site[data.i].addressCity = form.city;
      data.site[data.i].addressDistrict = form.district;
      data.site[data.i].addressDefaultAddress = form.defaultAddress;
      data.site[data.i].address = form.province+form.city+form.district+form.defaultAddress;
      data.site[data.i].tacitlyApprove = Number(form.tacitlyApprove);
      data.modificationFlag = false;
      data.flag = false;
      let modificationFlag = data.site[data.i];
      let codeModification = 400;
      proxy.$get("/api/PersonalCenter/addressAdministration", {...modificationFlag,codeModification})
          .then((date)=>{

          })
      ElMessage({
        message: '地址修改成功',
        type: 'success',
      })
      if (form.tacitlyApprove){
        data.site.forEach((item)=>{
          item.tacitlyApprove = false;
        })
        data.site[data.i].tacitlyApprove = true;
      }
      console.log(data.site[data.i].tacitlyApprove)
      form.recipients = '';
      form.phone = '';
      form.defaultAddress = '';
      form.tacitlyApprove = '';
      form.province = '';
      form.city = '';
      form.district = '';
      //添加确定
    }else {
      //创建obj
      let obj = {
        // id:data.site.length+1,
        name:form.recipients,
        phone:form.phone,
        address:form.province+form.city+form.district+form.defaultAddress,
        addressProvince:form.province,
        addressCity:form.city,
        addressDistrict:form.district,
        addressDefaultAddress:form.defaultAddress,
        tacitlyApprove:Number(form.tacitlyApprove),
        //添加
        codeAdd:200
      };
      proxy.$get("/api/PersonalCenter/addressAdministration", {...obj})
          .then((date)=>{
            data.site=date;
            console.log(data.site);
          })
      data.flag = false;
      // if (form.tacitlyApprove){
      //   data.site.forEach((item)=>{
      //     item.tacitlyApprove = false;
      //   })
      //   data.site[data.site.length-1].tacitlyApprove = true;
      // }
      data.site.push(obj);
      //清空
      form.recipients = '';
      form.phone = '';
      form.defaultAddress = '';
      form.tacitlyApprove = '';
      form.province = '';
      form.city = '';
      form.district = '';
      ElMessage({
        message: '地址添加成功',
        type: 'success',
      })
    }
  }
}
//打开添加地址
let open = ()=>{
  data.flag = true;
  data.isRemove = true;
}
//关闭添加地址
let close = ()=>{
  data.flag = false;
  data.phoneFlag = false;
  data.recipientsFlag = false;
  data.defaultAddressFlag = false;
  data.modificationFlag = '';
  form.recipients = '';
  form.phone = '';
  form.defaultAddress = '';
  form.tacitlyApprove = '';
  form.province = '';
  form.city = '';
  form.district = '';
}
//点击删除
let enRemove =()=>{
  data.flag = false;
  let n = data.site[data.n];
  let codeRemove = 300;
  //发送get请求
  proxy.$get("/api/PersonalCenter/addressAdministration", {...n,codeRemove})
      .then((date)=>{

      })
  data.site.splice(data.n,1);
  ElMessage({
    message: '地址删除成功',
    type: 'success',
  })
}
let enThink = ()=>{
  data.flag = false;
}

const opens = () => {
  ElMessageBox.alert(
    '<strong>此功能暂时未开发,请耐心等待</strong>',
    '温馨提示',
    {
      dangerouslyUseHTMLString: true,
    }
  )
}

</script>


<style lang="less" scoped>

.AH{
color:rgba(144, 141, 141, 0.8);
// white-space: nowrap;
text-overflow: ellipsis;
overflow: hidden;
display: -webkit-box; //
-webkit-line-clamp: 1; //显示两行，其余省略
-webkit-box-orient: vertical; //行数方向为垂直
}
.mask {
  width: 100%;
  height: 100%;
  position: fixed;
  left: 0;
  top: 0;
  background: rgba(0,0,0,.6);
  z-index: 999;
  //display: none;
  .mask-flag {
    min-width: 440px!important;
  }
  .mask-content {
    max-width: 680px;
    min-width: 550px;
    padding: 40px 65px;
    position: absolute;
    left: 50%;
    top: 50%;
    background: #fff;
    border-radius: 2px;
    transform: translate(-50%,-50%);
    text-align: center;
    .mask-content-body {
      width: 100%;
      background: #fff;
      border-radius: 2px;
      text-align: center;
      font-size: 14px;
      .rem {
        box-sizing: border-box;
        min-width: 440px;
        h3 {
          line-height: 24px;
          font-size: 18px;
          color: #303133;
        }
        div {
          display: flex;
          justify-content: space-between;
          .el-button {
            width: 164px;
            height: 40px;
          }
        }
      }
      div {
        position: relative;
        margin: 10px 0;
        .el-input {
          height: 50px;
        }
        h3 {
          padding: 0;
          margin-bottom: 40px;
          font-size: 22px;
        }
        .personalData-form-inp {
          .el-input {
            height: 50px;
          }
          input {
            width: 100%;
            height: 50px;
            padding: 0 25px;
            box-sizing: border-box;
            background-color: #fff;
            border-radius: 4px;
            border: 1px solid #dcdfe6;
          }
          .el-select {
            width: 165px;
            /deep/ .el-input__inner {
              height: 50px;
            }
          }
        }
        .el-form-item-inp {
          display: flex;
          justify-content: space-between;
        }
      }
      .hint {
        position: absolute;
        bottom: -20px;
        span {
          text-align: left;
          color: red;
          font-size: 12px;
        }
      }
      .confirm {
        display: flex;
        justify-content: start;
        /deep/ .el-button {
          width: 100%;
          height: 50px;
        }
      }
      .close {
        /deep/ .el-icon {
          position: absolute;
          right: -42px;
          top: -36px;
          font-size: 34px;
          color: #909399;
          cursor: pointer;
        }
      }
      .default {
        display: flex;
        justify-content: start;
      }
      .example-block {
        display: flex;
        justify-content: start;
        /deep/ .el-cascader {
          width: 100%;
          /deep/ input {
            height: 50px;
          }
        }
      }
    }
  }
}
 h1 {
     font-size: 20px;
     margin-top: 100px;
 }
a:hover {
    text-decoration: none !important;
    
}
.order {
    width: 1200px;
    margin-left:150px;
}
.header {
    margin-top:30px ;
    display: flex;
    align-items: center;
  flex-flow: wrap;
  &>div {
    margin-top: 24px;
  }
    .address {
      &.active {
        border: 1px solid #0096d6;
      }
      div{
        .addRes{
          color:red;
          border:1px solid red;
          border-radius: 3px;
          font-size:12px ;
        }
        .AHC{
.AH {
    width: 200px;
    display: -webkit-box;
    -webkit-line-clamp: 1;
    -webkit-box-orient: vertical;
    overflow: hidden;
  }
        }
       
      }
      margin-right: 22px;
         border: 1px solid rgb(233, 227, 227);
        border-radius: 5px;
         width: 208px;
        height: 158px;
        padding:0 34px;
      cursor: pointer;
        .defaults{
          display: -webkit-box;
            -webkit-line-clamp: 1;
            -webkit-box-orient: vertical;
            overflow: hidden;
.site {
    color: rgba(144, 141, 141, 0.799);
    
  }

  .default {
    color: red;
    border: 1px solid red;
    border-radius: 3px;
    font-size: 12px;
  }
        }
     
        .ico{
                padding-top: 24px;
                color: rgba(144, 141, 141, 0.799);
                font-size: 20px;
                display: flex;
                justify-content: flex-end;
            }
    }
   .new {
       border: 1px solid rgb(233, 227, 227);
     width: 276px;
       height: 158px;
       border-radius: 5px;
       display: flex;
       justify-content: center;
       align-items: center;
     cursor: pointer;
       img {
           width: 20px;
           height: 20px;
       }
   }
}

.discounts {
    margin: 60px 0;
    .discountsH {
        font-size: 16px;
        padding: 20px 0;
        border-top: 1px solid #ccc;
        border-bottom: 1px solid #ccc;

        div {
            margin:50px 0;
            a {
                color: deepskyblue;
                text-decoration: none;
            }
        }
    }
    .discountsW {
        padding: 10px 0;
        font-size: 16px;
        border-bottom: 1px solid #ccc;
        div {
            margin: 40px 0;
            input {
                margin-left: 120px;
            }

            span {
                margin: 0 20px;
            }
        }
    }
}
.payment {
    .paymentA {
        border-top: 1px solid #ccc;
    }
    h2 {
        font-size: 24px;
    }
    .paymentAA {
        margin: 50px 0;
        display: flex;
        align-items: center;
        justify-content: space-between;
        img{
          width: 100px;
          height: 100px;
        }
        .state{
            width: 200px;
        }
    }
}
.pay {
    display: flex;
    justify-content: flex-end;
    padding-bottom: 50px;
    background: white;
    div {
        margin-right: 0;
    }
    h1 {
        font-size: 20px;
    }
    span {
        font-size: 24px;
        color: deepskyblue;
    }
    .flex {
        padding-top: 20px;
        .flexA {
            width: 200px;
            height: 60px;
            text-decoration: none;
        }
    }
}
</style>
